from django.shortcuts import render,HttpResponse,HttpResponseRedirect
from django.http import JsonResponse
from django.urls import reverse
from app.neo4jHelper import helper
from app.neo4jHelper import relationHelper

from app.neo4jHelper import csvHelper
from django.conf import settings
from django.contrib.staticfiles.storage import staticfiles_storage
from app.modelHelper import load

import os
import random

# Create your views here.

def index(request):
    return (HttpResponse('欢迎使用！'))

def hello(request):
    return JsonResponse({'hello':'您已经成功和后端通信！这句话来自/backend/app/views.hello'})

def user_list(request):
    #优先去项目根目录寻找（当settings配置了templates路径时）
    #在app目录下的templates目录下寻找(根据app注册顺序，逐一去templates下寻找)
    return render(request,'user_list.html')

def tpl(request):
    h1 = "张三"
    h2 = ["李四",20,"ECUST"]
    h3 = {"姓名":"王五","age":21}
    data_list = [
        {"姓名":"王1","age":21},
        {"姓名":"王2","age":21}
    ]
    return render(
        request,
        'tpl.html',
        {
            "n1":h1,
            "n2":h2,
            "n3":h3,
            "n4":data_list
        },
        )
def news(request):  
    
    return render(request,'news.html',{'data_list':[]})

def login(request):  
    if request.method == "GET":
        return render(request,'login.html',{'result':0})
   
    user_name = request.POST.get("user")
    password = request.POST.get("password")
    if user_name == "admin" and password == "123":
        return HttpResponse("登陆成功")
    
    return render(request,'login.html',{'err_msg':"登陆失败"})

#展示药材信息
def medicine(request):
    node_list = request.session.get('node_list',[])
    selectType = request.session.get('selectType','')
    print('len(node list):',len(node_list))
    result = []
    if selectType =='中药材':
        for item in node_list:
            temp = {}
            temp['name'] = item['name']
            temp['id'] = item['ID']
            temp['拼音名称'] = item['拼音名称']
            result.append(temp)
    elif selectType == '中药组方':
        for item in node_list:
            temp = {}
            temp['name'] = item['n']['name']
            temp['id'] = item['n']['ID']
            temp['功能'] = item['n']['功能']
            result.append(temp)
    else:
        result = []
    print('len res:',len(result))
    # properties_dict = json.loads(properties)
    return render(request,"medicine.html",{'data':result})
#搜索
def search_1(request):
    """
    存在问题：路由没变，还是/search/,应该跳转到/info/medicne/

    解决办法1（成功）：
        当您从查询字符串参数中获取到properties字典后，我将它存储在Django的会话中，使用request.session['properties'] = properties语句。在medicine视图函数中，我使用request.session.get方法获取存储在会话中的properties字典，并将它传递给模板展示。
    解决办法2（未尝试）：
        您也可以考虑使用表单提交的方式来传递properties参数。例如，您可以在search视图函数中，将properties字典添加到一个隐藏的表单元素中，并将整个表单提交到medicine视图函数。在medicine视图函数中，您可以使用request.POST方法获取提交的表单数据，并从中提取出properties字典。
    """
    err_msg = ""
    if request.method == "GET":
        return render(request,"search.html",{"err_msg":err_msg})
    
    medicine = request.POST.get("medicine")
    node = helper.selectNodeByNodeName(medicine,"中药材")
    if node:
        properties = helper.getPropertyOnNode(node)
        request.session['properties'] = properties
        url = reverse("medicineInfo")
        return HttpResponseRedirect(url)
        
    else:
        return render(request,"search.html",{"err_msg":"查询失败，数据库没有此条目！"})

def test_axios(request):
    """
    测试返回axios请求的页面
    """
    return render(request,"axios.html")

def test_get(request):
    """
    测试返回axios请求数据
    """
    node = helper.selectNodeByNodeName("羌活","中药材")
    p = helper.getPropertyOnNode(node)
    # data = {"text":"hello axios!"}
    return JsonResponse(p)

def nodes_count(request):
    """
    参数:label
    返回label的结点数量
    """
    print("现在是在nodesCount里边！")
    label = request.GET.get('label')
    nums = helper.countNodesByLabel(label)
    result = {label:nums[0]['count']}
    return JsonResponse(result)

def search(request):
    """
    接收参数:selectMode
    返回查询结果列表
    """
    selectMode = int(request.GET.get('selectMode'))
    node_name = request.GET.get('nodeName')
    selectType = request.GET.get('selectType')
    result = helper.selectNodeByNodeName(node_name,selectType,selectMode)
    
    if result:
        result = helper.searchResultTransfer(result,selectType)
        print(result)
        return JsonResponse(result)

    else:
        error = {'error':'出错'}
        # return render(request,"search.html",{"err_msg":"查询失败，数据库没有此条目！"})
        return JsonResponse(error)
    
def downloadNode(request):
    """
    接收参数：
        -label:结点类型
    返回下载链接      
    """
    path = os.path.join(settings.BASE_DIR,'app','static','data','temp.csv')
    print(path)
    # label = request.GET('label')
    res = helper.selectNodesByLabel('PLAYER')
    csvList = csvHelper.getCSVList(res)
    csvHelper.save_csv(path,csvList) #先将结点保存在静态文件中

    file_url = staticfiles_storage.url('data/temp.csv')
    fileName = 'temp.csv'
    print(file_url)
    return JsonResponse({'url':file_url,'fileName':fileName})

def nodeInfo(request):
    nodeName = request.GET.get('nodeName')
    selectType = request.GET.get('selectType')
    # nodeName = "羌活胜湿汤"
    # selectType = "中药组方"
    node = helper.selectNode(nodeName,selectType)
    info = helper.getPropertyOnNode(node)
    # print("info:",info)

    return JsonResponse(info)

def nodeMessage(request):
    nodeID = request.GET.get('nodeID')
    selectType = request.GET.get('selectType')
    # nodeID = "herb00210"
    # selectType = "中药材"
    node = helper.selectNodeByID(nodeID,selectType)
    message = helper.getPropertyOnNode(node)
    print(message)

    return JsonResponse(message)

def getRelationNodes(request):
    result = {}
    nodeID = request.GET.get('nodeID')
    selectType = request.GET.get('selectType')
    # nodeID = "formul00211"
    # selectType = "中药组方"
    print('N1',nodeID)
    print('N2',selectType)
      
    relationNodeList,categories = relationHelper.relationNodeTransfer(nodeID,selectType)
    result['relationNodes'] = relationNodeList
    result['categories'] = categories

    # print("result:",result)
    return JsonResponse(result)
def getStats(request):
    result = {}
    nodes_label_list = request.GET.get('nodes_label_list').split(',')
    relations_label_list = request.GET.get('relations_label_list').split(',')
    # nodes_label_list = ['中药材','中药组方','化合物','靶点','来源植物名','疾病']
    # relations_label_list = ['方剂组成','靶点对应疾病','化合物对应靶点','药材组分','药材来源植物名']
    print(nodes_label_list)
    print(relations_label_list)
    nodes_count_list = helper.getNodesCount(nodes_label_list)
    relations_count_list = helper.getRelationsCount(relations_label_list)

    result['nodes_count'] = nodes_count_list
    result['relations_count'] = relations_count_list    
    return JsonResponse(result)

def getPaperText(request):
    result = {}
    # lang:en/zh
    lang = request.GET['text_label']
    # lang = "en"
    choice = str(random.randint(1,3))
    if lang == 'en':
        choice = str(random.randint(1,2))
    properties = helper.getText(lang,choice)
    print('choice:',choice)
    print('lang:',lang)
    print('properties:',properties)

    return JsonResponse(properties)

def getEntityResult(request):
    result = {}
    text = request.GET['text']
    # text = "常见的治疗高血压的方法之一是通过药物治疗来控制血压水平。一些常用的药物包括ACE抑制剂、钙通道阻滞剂和利尿剂等。这些药物通过不同的机制来降低血压，从而减少高血压患者的心血管风险。"
    response = load.extractEntities(text)
    # print('response',response)
    # entities = helper.evalResponse_1(response)
    result['entities'] = response

    print('result:',result)
    return JsonResponse(result)

def getRelationResult(request):
    nodes = []
    links = []
    text = request.GET['text']
    # text = "Background SARS-CoV-2 has caused millions of deaths, and, since Aug 11, 2020, 20 intramuscular COVID-19 vaccines \nhave been approved for use. We aimed to evaluate the safety and immunogenicity of an aerosolised adenovirus type-5 \nvector-based COVID-19 vaccine (Ad5-nCoV) in adults without COVID-19 from China."
    response = load.extractRelations(text)

    # nodes, links = helper.evalResponse(response)
    # result = {
    # 'nodes': nodes,
    # 'links': links
    # }
    result = response
    print('result:',result)
    return JsonResponse(result)

